import { useEffect } from "react";
import { useStore } from "@/store";
import { useLocation } from "react-router-dom";
import { nanoid } from "nanoid";
import SessionStorageService from "@/SessionStorageService";
import PPTEditBlock from "./components/PPTEditBlock";
import PPTContent from "./components/PPTContent";

const PPTDetail = () => {
  const {
    modifyPowerPointTitle,
    modifyPowerPoint,
    updatePowerPointIndex,
    modifyArbitraryValue,
  } = useStore();
  const { search } = useLocation();
  // 创建一个URLSearchParams对象
  const params = new URLSearchParams(search);
  // 获取title和id的值
  const query = {
    title: params?.get("title") || "",
    id: params?.get("id") || "",
  };

  useEffect(() => {
    window.focus();
    // 如果query存在且query.title存在，则调用modifyPowerPointTitle函数，传入query.title
    if (query && query.title) {
      modifyPowerPointTitle(query.title);
    }
    //  有id说明是编辑，需要找到一个index的item然后更新
    if (query && query.id) {
      // 从SessionStorageService中获取store，如果没有则赋值为空数组
      const sumBro = SessionStorageService.getItem("store") || [];
      // 在sumBro中查找id与query.id相等的item
      const itemFlag = sumBro.find((item) => item.id === query.id);
      // 如果找到了itemFlag
      if (itemFlag) {
        // 调用modifyPowerPointTitle函数，传入itemFlag.powerPointTitle
        modifyPowerPointTitle(itemFlag?.powerPointTitle);
        // 调用updatePowerPointIndex函数，传入1
        updatePowerPointIndex(1);
        // 调用modifyArbitraryValue函数，传入query.id和itemFlag.powerPointArr
        modifyArbitraryValue({
          powerPointParId: query.id,
          powerPointArr: itemFlag.powerPointArr,
          PPtBgtype: itemFlag.PPtBgtype,
          PPtBgValue1: itemFlag.PPtBgValue1,
          PPtBgValue2: itemFlag.PPtBgValue2,
        });
        // 调用modifyPowerPoint函数，传入itemFlag.powerPointArr
        modifyPowerPoint(itemFlag.powerPointArr);
      }
    } else {
      // 如没有id，说明是新建，
      // 1、需要初始化我们slideList
      // 2、需要更新当前索引为0
      // 调用updatePowerPointIndex函数，传入1
      updatePowerPointIndex(1);
      // 调用modifyPowerPoint函数，传入一个包含sortId为1，id为nanoid()，elements为空数组的对象
      modifyPowerPoint([
        {
          sortId: 1,
          id: nanoid(),
          elements: [],
        },
      ]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div
      // 设置样式
      style={{
        // 设置flex属性，使其占据剩余空间
        flex: 1,
        // 设置宽度，使其宽度为100%减去200px
        width: "calc(100%)",
        // 设置高度，使其高度为100%
        height: "100%",
      }}
    >
      <PPTEditBlock />
      <PPTContent />
    </div>
  );
};

export default PPTDetail;
